import Vue from 'vue'
import VueRouter from 'vue-router'
import Page404 from '@/views/Page404.vue'
// 引入log页面
const Log = () => import('@/views/log.vue')
// 引入layout页面
const Layout = () => import('@/views/layout.vue')
// 引入articles页面
const Articles = () => import('@/views/articles.vue')
// 引入edit(编辑)页面
const Edit = () => import('@/views/edit.vue')
// 引入image(素材)页面
const Image = () => import('@/views/image.vue')
// 引入add(发布文章)页面
const Add = () => import('@/views/add.vue')
// 引入home页面
const Homee = () => import('@/views/home.vue')
// 引入comment(评论管理)页面
const Comment = () => import('@/views/comment.vue')
// 引入fans(粉丝管理)页面
const Fans = () => import('@/views/fans.vue')
// 引入settings(个人设置)页面
const Settings = () => import('@/views/settings.vue')
Vue.use(VueRouter)
// 路由规则
const routes = [
  {
    path: '/log',
    component: Log
  },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/articles', component: Articles },
      { path: '/image', component: Image },
      { path: '/edit/:id', component: Edit },
      { path: '/add', component: Add },
      // { path: '/home', component: Home },
      { path: '', component: Homee },
      { path: '/comment', component: Comment },
      { path: '/fans', component: Fans },
      { path: '/settings', component: Settings }
    ]
  },
  {
    path: '*', component: Page404
  }
]
const router = new VueRouter({
  routes
})
// 路由导航
router.beforeEach((to, from, next) => {
  // 如果去layout页面先检查有没有token，如果有方行，如果没有则回登入页面
  // 检查是否有token
  const tokenStr = localStorage.getItem('tokenStr')
  const pageList = ['/', '/articles']
  if (pageList.includes(to.path)) {
    if (tokenStr) {
      // 方行
      next()
    } else {
      // 回登陆页
      alert('没有token，不能访问主页')
      next('/log')
    }
  } else {
    next()
  }
})
export default router
